﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;

// 16 september - Updated the filter
//- Copy the KB to the c :\MSU location
//- Browse to the location c:\MSU
//- Create new folder kb
//- Expand -f:* c:\MSU\Windows6.1-KB2686831-x64.msu c:\MSU\kb
//- Browse to the location c:\MSU\kb
//- Create new folder as "CAB"
//- Expand -f:* c:\MSU\kb\Windows6.1-KB2686831-x64.cab c:\MSU\kb\CAB   ******till here done***
//- Run the command
//- pkgmgr /ip /m:c:\MSU\kb\CAB\update-bf.mum
//- Reboot the server
//23 September - enabled the pkgmr command. having issues with the parameters.
// 1 October - Fixed the issue with PKGMGR parameters. Now final touchup required.
// adding functionality to remove existing MSU folder 
// Added better exception handling
//3 October - Fixed issues with folder creation and deleting. 
//Created a new thread to invoke pkgmgr
//Created a logfile of the process
//Ready to publish




namespace LDRInstaller
{
    public partial class Form1 : Form
    {
        string cmd1;
        string HotfixFileName;
        string HotfixDestinationPath;
        string cmd2;
        string HotfixCabFilePath;
        string HotfixCabFileName;
        string cmd3;
        

        public Form1()
        {
            InitializeComponent();
            

        }

        public void PKGMGRStartThread()
        {
            PKGExecuteCommandSync(cmd3);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //will show only msu files
            //openFileDialog1.Filter = "Hotfix Executable | *.msu";  
            // will show either msu or exe depending on what u select
            //openFileDialog1.Filter = "All Exes (*.exe)|*.exe |Hotfix Executable (*.msu)| *.msu"; 
            

            openFileDialog1.Filter = "Hotfix Executable Files (*.exe, *.msu)|*.msu;*.exe";
            openFileDialog1.Title = "Select the KB Update File";
            //openFileDialog1.InitialDirectory = @"c:\";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                textBox1.Text = openFileDialog1.FileName.ToString();
            textBox2.Text= "File selected: " + textBox1.Text;
            textBox2.AppendText("\n");
        }

        private void button2_Click(object sender, EventArgs e)
        {

           

            if (Directory.Exists(@"C:\\TEMP\\MSU"))
            {

                textBox2.AppendText("Directory already present. Deleting -  C:\\TEMP\\MSU\\* \n");

                try
                {
                    DirectoryInfo di = new DirectoryInfo(@"C:\\TEMP\\MSU");
                    di.Delete(true);
                }
                catch (Exception exception)
                {
                    textBox2.AppendText(exception.Message);
                    textBox2.AppendText("\n");
                }


            }

            Directory.CreateDirectory(@"C:\\TEMP\\MSU\\KB\\CAB");
            textBox2.AppendText("Directory structure created - C:\\TEMP\\MSU\\KB\\CAB \n");
            


            Directory.SetCurrentDirectory("c:\\TEMP\\MSU");
            textBox2.AppendText("Setting current directory to: " + Directory.GetCurrentDirectory().ToString() + "\n");
            
             HotfixFileName = Path.GetFileName(textBox1.Text);
             HotfixDestinationPath = "c:\\TEMP\\MSU\\"+HotfixFileName;

            try
            {
                File.Copy(textBox1.Text, HotfixDestinationPath,true);
                textBox2.AppendText("Hotfix file copied to " + HotfixDestinationPath + "\n");
            }
            catch (Exception ex)
            {
                textBox2.AppendText(ex.Message);
                textBox2.AppendText("\n");
            }

            
            cmd1 = "Expand -f:* "+ HotfixDestinationPath +" c:\\TEMP\\MSU\\KB";
            textBox2.AppendText("Extracting the files... \n");
            textBox2.AppendText(cmd1);
           ExecuteCommandSync(cmd1);

           
           HotfixCabFileName = HotfixFileName.Replace("msu", "cab");
           HotfixCabFilePath = "C:\\TEMP\\MSU\\KB\\" + HotfixCabFileName;

           try
           {

               if (File.Exists(HotfixCabFilePath))
               {
                   textBox2.AppendText("Trying to extract the cabfiles now... \n");
               }

               else
               {
                   textBox2.AppendText("Cab file missing.. Did you rename the original file: \n\n");
               }


               // HotfixCabFileName = Path.GetFileNameWithoutExtension(Directory.GetCurrentDirectory());
               cmd2 = "Expand -f:* " + HotfixCabFilePath + " c:\\TEMP\\MSU\\KB\\CAB";
               textBox2.AppendText(cmd2 + "\n");
               ExecuteCommandSync(cmd2);

           }
           catch (Exception exp1)
           {
               textBox2.AppendText(exp1.Message);
               textBox2.AppendText("\n");
           }

            //starting 23 Sept

                               
           if (File.Exists("c:\\TEMP\\MSU\\KB\\CAB\\update-bf.mum"))
           {
               

               if (checkBox1.Checked == true)
                   cmd3 = "/ip /m:c:\\TEMP\\MSU\\KB\\CAB\\update-bf.mum /quiet";
               else 
                    cmd3 = "/ip /m:c:\\TEMP\\MSU\\KB\\CAB\\update-bf.mum";
               textBox2.AppendText("Invoking PKGMGR now: \n");
               textBox2.AppendText("PKGMGR " + cmd3 + "\n");
               textBox2.AppendText("You cab safely close this application now \n");
               //calling function to save the logs 
               SaveLogs();

               //Starting PKGMGR 
               //PKGExecuteCommandSync(cmd3);

               //Starting PKGMGR using a new thread
               Thread Thread1 = new Thread(new ThreadStart(PKGMGRStartThread));
                Thread1.Start();

               
           }
           else
           {
               textBox2.AppendText("\n Update-BF.mum missing...");
           }




         }

       

        public void ExecuteCommandSync(string command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
                // /c tells cmd that we want it to execute the command that follows and then exit.
                
               System.Diagnostics.ProcessStartInfo procStartInfo =
               new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);
                        
               textBox2.AppendText("In ExecuteCommandSyncFunction the value of command is: " + command + "\n");

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
                textBox2.AppendText(result);
            }
            catch (Exception objException)
            {
                textBox2.AppendText("In ExecuteCommandSyncFunction exception : " + objException.Message + "\n");// Log the exception
            }
        }

        public void PKGExecuteCommandSync(string command)
        {
            try
            {
                
                System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo("pkgmgr.exe");
                procStartInfo.Arguments = command;
                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamR+eader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();
                textBox2.AppendText(result);
            }
            catch (Exception objException)
            {
                textBox2.AppendText(objException.ToString());// Log the exception
            }
        }

        public void SaveLogs()
        {
            string fname = "LDRInstallerLog.txt";
            StreamWriter sw = new FileInfo(fname).CreateText();
            sw.WriteLine("=============================================");
            sw.WriteLine("Logging started at" + DateTime.Now.ToLongTimeString());
            sw.WriteLine("cmd1: " +   cmd1);
            sw.WriteLine("HotfixFileName: " + HotfixFileName);
            sw.WriteLine("HotfixDestinationPath: " + HotfixDestinationPath);
            sw.WriteLine("cmd2: " +  cmd2);
            sw.WriteLine("HotfixCabFilePath: " + HotfixCabFilePath);
            sw.WriteLine("HotfixCabFileName: " + HotfixCabFileName);
            sw.WriteLine("cmd3: " + cmd3);
            sw.WriteLine("=============================================");
            try
            {
                foreach (string s in textBox2.Lines)
                {
                    sw.WriteLine(s);
                }
            }
            catch (Exception re)
            {
                textBox2.AppendText(re.Message);
            }
            sw.Flush();
            sw.Close();
        }

      
    }
}

